<template>
  <div class="container">
    <el-card v-loading="loading" class="box-card">
      <el-breadcrumb
        separator-class="el-icon-arrow-right"
        v-if="subjectIds.id && subjectIds.name"
      >
        <el-breadcrumb-item>学科管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{
          subjectIds.id ? subjectIds.name : ""
        }}</el-breadcrumb-item>
        <el-breadcrumb-item>标签管理</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 搜索栏 -->
      <el-row type="flex" class="sousuo">
        <el-col :span="18">
          <el-row>
            <el-col :span="13.5">
              <el-form label-width="80px" :inline="true">
                <el-form-item label="标签名称">
                  <el-input
                    size="small"
                    v-model="formInline.tagName"
                  ></el-input>
                </el-form-item>
                <el-form-item label="状态">
                  <el-select
                    size="small"
                    v-model="formInline.state"
                    placeholder="请选择"
                  >
                    <el-option label="启用" value="1"></el-option>
                    <el-option label="禁用" value="0"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="5">
              <el-button @click="onReset" size="small">清除</el-button>
              <el-button type="primary" size="small" @click="onSubmit"
                >搜索</el-button
              >
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="6">
          <el-row type="flex" justify="end">
            <el-button
              v-if="subjectIds.id && subjectIds.name"
              type="text"
              icon="el-icon-back"
              @click="$router.back()"
              >返回学科</el-button
            >
            <el-button
              @click="dialogAdd = true"
              icon="el-icon-edit"
              type="success"
              size="small"
              >新增标签</el-button
            >
          </el-row>
        </el-col>
      </el-row>
      <el-alert class="alert" type="info" show-icon :closable="false">
        <template slot="title">
          <span>数据一共 {{ page.counts }} 条</span>
        </template>
      </el-alert>
      <!-- 表格数据 -->
      <el-table
        :data="tableData"
        :header-cell-style="headerClass"
        style="width: 100%"
      >
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="所属学科" prop="subjectName"></el-table-column>
        <el-table-column label="标签名称" prop="tagName"></el-table-column>
        <el-table-column label="创建者" prop="username"></el-table-column>

        <el-table-column label="创建日期" prop="addDate">
          <template slot-scope="{ row }">{{
            row.addDate | parseTimeByString
          }}</template>
        </el-table-column>
        <!-- <el-table-column label="面试题数量" prop="totals"></el-table-column> -->
        <el-table-column
          label="状态"
          prop="state"
          :formatter="formatDisctorys"
        ></el-table-column>

        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" @click="changeState(row)">
              {{ row.state === 1 ? "禁用" : "启用" }}
            </el-button>
            <el-button
              type="text"
              :disabled="row.state === 1"
              @click="dialogEditShow(row)"
              >修改</el-button
            >
            <el-button
              type="text"
              :disabled="row.state === 1"
              @click="remove(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="end" class="pagination" align="middle">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.page"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="page.pagesize"
          layout=" prev, pager, next, sizes, jumper"
          :total="page.counts"
        ></el-pagination>
      </el-row>
    </el-card>
    <!-- 新增目录弹框 -->
    <el-dialog
      title="新增目录"
      :visible.sync="dialogAdd"
      width="30%"
      @close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="30%"
      >
        <el-form-item
          v-if="!subjectIds.id && !subjectIds.name"
          label="所属学科"
        >
          <el-select
            v-model="ruleForm.value"
            @focus="getsimple"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in simpleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="ruleForm.tagName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改目录弹框 -->
    <el-dialog
      title="修改目录"
      :visible.sync="dialogEdit"
      width="30%"
      @close="handleCloseEdit"
    >
      <el-form
        :model="editRuleForm"
        :rules="rules"
        ref="editruleForms"
        label-width="30%"
      >
        <el-form-item
          v-if="!subjectIds.id && !subjectIds.name"
          label="所属学科"
        >
          <el-select
            v-model="editRuleForm.value"
            @focus="getsimple"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in simpleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="editRuleForm.tagName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEdit = false">取 消</el-button>
        <el-button type="primary" @click="btnOkEdit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, changeState, add, update, remove } from '@/api/hmmm/tags'
// import DisctorysEnum from '@/api/base/baseApi'
import { simple } from '@/api/hmmm/subjects'
export default {
  components: {},

  data () {
    return {
      loading: false,
      dialogAdd: false, // 控制新增弹层的显示
      dialogEdit: false, // 控制修改的显示
      // 搜索表单数据
      formInline: {
        tagName: '',
        state: null
      },
      // 添加目录数据
      ruleForm: {
        tagName: '',
        value: ''
      },
      // 修改目录数据
      editRuleForm: {
        tagName: '',
        value: ''
      },
      // 表单验证
      rules: {
        tagName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ]
      },
      tableData: [], // 接数据
      page: {
        page: 1, // 当前页码
        pagesize: 10, // 每页的数据量
        counts: 0 // 总数
      },
      wwzzID: '', // 请求数据id 放在路径上的
      subjectID: null, // 学科id
      // 学科简单数据列表
      simpleList: []
    }
  },
  created () {
    this.getList()
  },

  methods: {
    // 表头颜色的回调函数
    headerClass () {
      return 'background:#fafafa'
    },
    // 获取目录数据
    async getList (formInline) {
      this.loading = true
      try {
        // 判断是否有学科id 有的话 请求的时候加上学科id 获取到的就是当前学科id的数据
        const { data } = this.subjectIds.id
          ? await list({
            ...this.page,
            subjectID: this.subjectIds.id,
            ...formInline
          })
          : await list({ ...this.page, ...formInline })
        this.page.counts = data.counts
        this.tableData = data.items
      } catch (error) {
        this.$message.error('请求失败')
      }
      this.loading = false
    },
    // 格式化状态
    formatDisctorys (row, column, cellValue, index) {
      // 利用find找对应的值
      // const obj = DisctorysEnum.status.find((item) => +item.id === cellValue)
      return cellValue === 1 ? '已启用' : '已禁用'
      // return obj ? obj.value : '未知'
    },
    // 点击搜索框清除按钮
    onReset () {
      this.formInline = {
        tagName: '',
        state: null
      }
    },
    // 点击搜索
    async onSubmit () {
      this.getList(this.formInline)
    },
    // 选择每页条数
    handleSizeChange (val) {
      this.page.pagesize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.page.page = val
      this.getList()
    },
    // 改变状态
    async changeState (data) {
      try {
        // 判断state是否等于1
        data.state = data.state === 1 ? 0 : 1
        await changeState({ ...data, state: data.state })
        this.$message({ message: '操作成功', type: 'success' })
      } catch (error) {
        this.$message.error('操作失败,请稍后再试')
      }
    },
    // 获取学科简单列表
    async getsimple () {
      try {
        const { data } = await simple()
        this.simpleList = data
      } catch (error) {
        console.log(error)
      }
    },
    // 显示修改弹框 dialogEditShow
    dialogEditShow (row) {
      this.editRuleForm.value = row.subjectID
      this.wwzzID = row.id
      this.editRuleForm.tagName = row.tagName
      this.dialogEdit = true
    },
    // 修改目录
    async btnOkEdit () {
      try {
        await this.$refs.editruleForms.validate()
        if (this.subjectIds.id && this.subjectIds.name) {
          await update({
            id: this.wwzzID,
            subjectID: +this.subjectIds.id,
            tagName: this.editRuleForm.tagName
          })
          this.$message.success('修改目录成功')
          this.dialogEdit = false
          // this.getList()
          if (!this.formInline.tagName && !this.formInline.state) {
            this.getList()
          } else {
            this.onSubmit()
          }
        } else {
          await update({
            id: this.wwzzID,
            subjectID: this.editRuleForm.value,
            tagName: this.editRuleForm.tagName
          })
          this.$message.success('修改目录成功')
          this.dialogEdit = false
          if (!this.formInline.tagName && !this.formInline.state) {
            this.getList()
          } else {
            this.onSubmit()
          }
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 添加目录
    async btnOk () {
      await this.$refs.ruleForm.validate()
      try {
        if (this.subjectIds.id && this.subjectIds.name) {
          await add({
            subjectID: +this.subjectIds.id,
            tagName: this.ruleForm.tagName
          })
          this.$message.success('新增目录成功')
          this.dialogAdd = false
          if (!this.formInline.tagName && !this.formInline.state) {
            this.getList()
          } else {
            this.onSubmit()
          }
        } else {
          await add({
            subjectID: this.ruleForm.value,
            tagName: this.ruleForm.tagName
          })
          this.$message.success('新增目录成功')
          this.dialogAdd = false
          if (!this.formInline.tagName && !this.formInline.state) {
            this.getList()
          } else {
            this.onSubmit()
          }
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 删除
    async remove (row) {
      try {
        await this.$confirm('此操作将永久删除该学科, 是否继续?', '提示', {
          type: 'warning'
        })
        await remove(row)
        // 解决页码当前页数据删除完之后页码显示bug问题
        if (this.tableData.length === 1) {
          this.page.page = this.page.page > 1 ? this.page.page - 1 : 1
        }
        this.getList()
        this.$message.success('删除成功!')
      } catch (error) {
        console.log(error)
      }
    },
    // 重置添加表单
    handleClose () {
      this.$refs.ruleForm.resetFields()
      this.ruleForm.value = ''
      this.dialogAdd = false
    },
    // 重置修改表单
    handleCloseEdit () {
      this.$refs.editruleForms.resetFields()
      // this.editRuleForm.value = ''
      this.editRuleForm = {
        tagName: '',
        value: ''
      }
      this.dialogEdit = false
    }
  },

  computed: {
    // 从地址中获取到数据
    subjectIds () {
      return this.$route.query || null
    }
  }
}
</script>
<style  scoped lang='scss'>
.container {
  padding: 10px 8px;
}
.alert {
  margin-bottom: 15px;
}
.pagination {
  margin-top: 15px;
}
.el-breadcrumb {
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}
.el-card__body {
  padding: 20px;
}
.sousuo {
  margin-top: 10px;
}
</style>
